<template>
  <div class="dashboard">
    <!-- Top Section: Pie Chart and Summary Table -->
    <div class="top-section">
      <div class="chart-container pie-chart-container">
        <input 
          type="month" 
          v-model="selectedMonth" 
          @change="fetchPieChartData" 
          class="month-picker"
        />
        <canvas id="pieChart"></canvas>
      </div>
      <div class="summary-table">
        <table>
            <thead>
              <tr>
                <th>指标</th>
                <th>金额 (元)</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td>总销售金额</td>
                <td>{{ formatCurrency(salesTotal) }}</td>
              </tr>
              <tr>
                <td>收入总计</td>
                <td>{{ formatCurrency(incomeTotal) }}</td>
              </tr>
              <tr>
                <td>支出总计</td>
                <td>{{ formatCurrency(outcomeTotal) }}</td>
              </tr>
              <tr v-for="(amount, label) in pieChartData" :key="label">
                <td>{{ label }}</td>
                <td>{{ formatCurrency(amount) }}</td>
              </tr>
            </tbody>

        </table>
      </div>
    </div>
    <div class="bottom-section">
      <div class="chart-container">
        <canvas id="salesChart"></canvas>
      </div>
      <div class="chart-container">
        <canvas id="incomeOutcomeChart"></canvas>
      </div>
    </div>
  </div>
</template>

<script>
import { watch } from 'vue';
import axios from 'axios';
import Chart from 'chart.js/auto';
import { ref, onMounted } from 'vue';
import ChartDataLabels from 'chartjs-plugin-datalabels';
Chart.register(ChartDataLabels); // 确保插件注册


export default {
  setup() {
    const hasReloaded = ref(true);
    const pieChart = ref(null);
    const salesChart = ref(null);
    const incomeOutcomeChart = ref(null);

    const selectedMonth = ref('2024-07'); 
    const salesTotal = ref(0);
    const incomeTotal = ref(0);
    const outcomeTotal = ref(0);
    const pieChartData = ref({});

    const formatCurrency = (amount) => {
      return new Intl.NumberFormat('zh-CN', { minimumFractionDigits: 2 }).format(amount);
    };

    const calculatePercentage = (amount) => {
      const total = salesTotal.value + incomeTotal.value + outcomeTotal.value;
      return total ? ((amount / total) * 100).toFixed(2) : 0;
    };

    const fetchPieChartData = async () => {
  console.log('Selected month:', selectedMonth.value); // Debugging line
  const userId = localStorage.getItem('userId');
  if (!userId) {
    alert('请先登录');
    this.$router.push('/login');
    return;
  }

  try {
    const response = await axios.get('http://82.156.19.25:5000/api/plancome/piechart', {
      params: {
        month: selectedMonth.value,
        userId: userId
      }
    });

    console.log('API response:', response.data); // Debugging line

    if (response.data) {
      pieChartData.value = response.data;
      renderPieChart(response.data);
    } else {
      console.error('No data returned from the API');
    }
  } catch (error) {
    console.error('Error fetching pie chart data:', error);
  }
};


const renderPieChart = (data) => {
  const canvas = document.getElementById('pieChart');
  if (!canvas) {
    console.error('Canvas element with id "pieChart" not found');
    return;
  }

  const ctx = canvas.getContext('2d');
  if (!ctx) {
    console.error('Failed to get canvas context for pie chart');
    return;
  }

  if (pieChart.value) {
    pieChart.value.destroy();
  }

  pieChart.value = new Chart(ctx, {
    type: 'pie',
    data: {
      labels: Object.keys(data),
      datasets: [{
        data: Object.values(data),
        backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56', '#F39C', '#9B59B6', '#1ABC9C', '#F39C12'],
        borderWidth: 1,
        borderColor: '#ffffff',
      }]
    },
    options: {
      responsive: true,
      plugins: {
        legend: {
          position: 'bottom',
          labels: {
            font: {
              size: 14
            }
          }
        },
        tooltip: {
          callbacks: {
            label: function(tooltipItem) {
              const label = tooltipItem.label || '';
              const value = tooltipItem.raw || 0;
              const total = tooltipItem.chart._metasets[0].total;
              const percentage = ((value / total) * 100).toFixed(2);
              return `${label}: ${formatCurrency(value)} (${percentage}%)`;
            }
          },
          backgroundColor: '#333',
          titleColor: '#fff',
          bodyColor: '#fff',
          borderColor: '#fff',
          borderWidth: 1
        },
        datalabels: {
          color: '#fff',
          font: {
            weight: 'bold',
            size: 14
          },
          formatter: (value, ctx) => {
            const total = ctx.chart._metasets[0].total;
            const percentage = ((value / total) * 100).toFixed(2);
            return `${percentage}%`;
          }
        },
        title: {
          display: true,
          text: '销售成本和计划',
          font: {
            size: 18,
            weight: 'bold'
          }
        }
      }
    },
    plugins: [ChartDataLabels]
  });
};

    const fetchSalesChart = async () => {
      const userId = localStorage.getItem('userId');
      if (!userId) {
        alert('请先登录');
        this.$router.push('/login');
        return;
      }
      try {
        const response = await axios.get(`http://82.156.19.25:5000/sales_chart?user_id=${userId}`);
        const data = response.data;
        renderSalesChart(data);
        salesTotal.value = data.totals.reduce((acc, curr) => acc + parseFloat(curr), 0);
      } catch (error) {
        console.error('获取销售数据时出错:', error);
      }
    };
    const renderSalesChart = (data) => {
  const ctx = document.getElementById('salesChart').getContext('2d');
  if (salesChart.value) {
    salesChart.value.destroy();
  }
  salesChart.value = new Chart(ctx, {
    type: 'line',
    data: {
      labels: data.months,
      datasets: [{
        label: '总销售金额',
        data: data.totals.map(value => parseFloat(value)),
        borderColor: 'rgba(75, 192, 192, 1)',
        backgroundColor: 'rgba(75, 192, 192, 0.2)',
        borderWidth: 3,
        pointBackgroundColor: 'rgba(75, 192, 192, 1)',
        pointBorderColor: '#fff',
        pointBorderWidth: 2,
        pointRadius: 5,
        lineTension: 0.3
      }]
      
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          position: 'top',
          labels: {
            color: '#333',
            font: {
              size: 14
            }
          }
        },
        tooltip: {
          backgroundColor: '#fff',
          titleColor: '#333',
          bodyColor: '#666',
          borderColor: '#ddd',
          borderWidth: 1
        },
        title: {
          display: true,
          text: '每月销售预测',
          font: {
            size: 18,
            weight: 'bold'
          }
        }
      },
      scales: {
        x: {
          title: {
            display: true,
            text: '月份',
            color: '#333',
            font: {
              size: 14
            }
          },
          ticks: {
            color: '#666'
          }
        },
        y: {
          title: {
            display: true,
            text: '总金额',
            color: '#333',
            font: {
              size: 14
            }
          },
          ticks: {
            color: '#666'
          }
        }
      }
    }
  });
};


    const fetchIncomeOutcomeChart = async () => {
      const userId = localStorage.getItem('userId');
      if (!userId) {
        alert('请先登录');
        this.$router.push('/login');
        return;
      }
      try {
        const response = await axios.get(`http://82.156.19.25:5000/api/monthly-data?user_id=${userId}`);
        const { income, outcome } = response.data;

        const months = [];
        const incomeAmounts = [];
        const outcomeAmounts = [];

        let totalIncome = 0;
        let totalOutcome = 0;

        income.forEach(item => {
          const monthIndex = months.indexOf(item.month);
          if (monthIndex === -1) {
            months.push(item.month);
            incomeAmounts.push(parseFloat(item.total_income));
            outcomeAmounts.push(0);
            totalIncome += parseFloat(item.total_income);
          } else {
            incomeAmounts[monthIndex] = parseFloat(item.total_income);
            totalIncome += parseFloat(item.total_income);
          }
        });

        outcome.forEach(item => {
          const monthIndex = months.indexOf(item.month);
          if (monthIndex === -1) {
            months.push(item.month);
            incomeAmounts.push(0);
            outcomeAmounts.push(parseFloat(item.total_outcome));
            totalOutcome += parseFloat(item.total_outcome);
          } else {
            outcomeAmounts[monthIndex] = parseFloat(item.total_outcome);
            totalOutcome += parseFloat(item.total_outcome);
          }
        });

        renderIncomeOutcomeChart(months, incomeAmounts, outcomeAmounts);
        incomeTotal.value = totalIncome;
        outcomeTotal.value = totalOutcome;

      } catch (error) {
        console.error('Error fetching income and outcome data:', error);
      }
    };

    const renderIncomeOutcomeChart = (months, income, outcome) => {
  const ctx = document.getElementById('incomeOutcomeChart').getContext('2d');
  if (incomeOutcomeChart.value) {
    incomeOutcomeChart.value.destroy();
  }

  incomeOutcomeChart.value = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: months,
      datasets: [
        {
          label: '收入总计',
          data: income,
          backgroundColor: 'rgba(75, 192, 192, 0.6)',
          borderColor: 'rgba(75, 192, 192, 1)',
          borderWidth: 1,
          hoverBackgroundColor: 'rgba(75, 192, 192, 0.8)'
        },
        {
          label: '支出总计',
          data: outcome,
          backgroundColor: 'rgba(255, 99, 132, 0.6)',
          borderColor: 'rgba(255, 99, 132, 1)',
          borderWidth: 1,
          hoverBackgroundColor: 'rgba(255, 99, 132, 0.8)'
        }
      ]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          position: 'top',
          labels: {
            color: '#333',
            font: {
              size: 14
            }
          }
        },
        tooltip: {
          backgroundColor: '#fff',
          titleColor: '#333',
          bodyColor: '#666',
          borderColor: '#ddd',
          borderWidth: 1
        },
        title: {
          display: true,
          text: '现金收入支出',
          font: {
            size: 18,
            weight: 'bold'
          }
        }
      },
      scales: {
        x: {
          title: {
            display: true,
            text: '月份',
            color: '#333',
            font: {
              size: 14
            }
          },
          ticks: {
            color: '#666'
          }
        },
        y: {
          title: {
            display: true,
            text: '总金额',
            color: '#333',
            font: {
              size: 14
            }
          },
          ticks: {
            color: '#666'
          }
        }
      }
    }
  });
};


    onMounted(() => {
      if (!hasReloaded.value) {
        window.location.reload();
        hasReloaded.value = false;
      }
      fetchPieChartData();
      fetchSalesChart();
      fetchIncomeOutcomeChart();
    });

    watch(selectedMonth, () => {
      fetchPieChartData();
    });
    return {
      selectedMonth,
      pieChartData,
      salesTotal,
      incomeTotal,
      outcomeTotal,
      formatCurrency,
      calculatePercentage
    };
  }
};

</script>

<style scoped>
.dashboard {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px;
}

.top-section {
  display: flex;
  gap: 20px;
}

.bottom-section {
  display: flex;
  gap: 20px;
}

.chart-container {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background-color: #f8f9fa;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.pie-chart-container {
  max-width: 400px;
}

.month-picker {
  margin-bottom: 10px;
  padding: 5px;
  font-size: 14px;
  border: 1px solid #ddd;
  border-radius: 5px;
  box-shadow: none;
}

.summary-table {
  flex: 1;
  border: 1px solid #ddd;
  border-radius: 8px;
  background-color: #f8f9fa;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.summary-table table {
  width: 100%;
  border-collapse: collapse;
}

.summary-table th, .summary-table td {
  padding: 10px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

.summary-table th {
  background-color: #e9ecef;
  font-weight: bold;
}

.summary-table tbody tr:last-child td {
  border-bottom: none;
}
</style>
